package com.zzyl.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.zzyl.constant.Constants;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.google.common.collect.Lists;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.mockito.internal.matchers.Contains;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    public LoginVo login(UserLoginRequestDto userLoginRequestDto) throws IOException {
        //1.获取 小程序 传递的code，发起 远程调用 获取openId
        String openId=weChatService.getOpenId(userLoginRequestDto.getCode());
        //2.根据openId 查询数据库，查询用户
        Member member=memberMapper.getByOpenId(openId);
        //3.用户为空，构建一个用户对象，赋值openId
        if(ObjectUtil.isEmpty(member)){
            member=Member.builder().openId(openId).build();
        }
        //4，根据detail.code 发起请求获取真实的手机号
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());
        //5.根据不同情况新增/更新
        saveOrUpdate(member,phone);
        //6.生成token返回（包含用户ID和昵称）
        HashMap<String,Object>map =new HashMap<>();
        map.put(Constants.JWT_USERID,member.getId());
        map.put(Constants.JWT_USERNAME,member.getName());

        String jwt= JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(),map);

        //7.封装LoginVo 对象返回

        LoginVo loginVo=new LoginVo();
        loginVo.setToken(jwt);
        loginVo.setNickName(member.getName());

        return loginVo;
    }

    private void saveOrUpdate(Member member, String phone) {
        if (!phone.equals(member.getPhone())){
            member.setPhone(phone);
        }
        if(!ObjectUtil.isEmpty(member.getId())){
            memberMapper.update(member);
        }
        String phoneStr =phone.substring(7);
        Random random=new Random();
        int index=random.nextInt(DEFAULT_NICKNAME_PREFIX.size());
        String nickNames=DEFAULT_NICKNAME_PREFIX.get(index)+phoneStr;
        member.setName(nickNames);
        memberMapper.save(member);

    }
    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
}
